package cloud.xlh.digital_power_order.config.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2022/6/30 20:49
 * @ Description:
 */

@Configuration
public class RabbitMQConfig {

    // 普通订单Exchange
    @Bean("commonOrderExchange")
    public Exchange commonOrderExchange() {
        return ExchangeBuilder.topicExchange(RabbitMQConstant.COMMON_ORDER_EXCHANGE_NAME).durable(true).build();
    }

    // 普通订单事件队列
    @Bean("commonOrderEventQueue")
    public Queue commonOrderEventQueue() {
        return new Queue(RabbitMQConstant.COMMON_ORDER_EVENT_QUEUE_NAME);
    }

    // 普通订单Exchange和普通订单事件队列绑定关系
    @Bean
    public Binding commonOrderExchangeBindingCommonOrderEventQueue(@Qualifier("commonOrderEventQueue") Queue queue,
                                                             @Qualifier("commonOrderExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(RabbitMQConstant.ORDER_BACK_QUERY_ROUTING_KEY).noargs();
    }

    // 死信Exchange
    @Bean("deadLetterExchange")
    public Exchange deadLetterExchange() {
        return ExchangeBuilder.topicExchange(RabbitMQConstant.DEAD_LETTER_EXCHANGE).durable(true).build();
    }

    // 订单延迟过期队列，绑定死信队列，可指定路由key
    @Bean("orderDelayExpireQueue")
    public Queue orderDelayExpireQueue() {
        Map<String, Object> args = new HashMap<>(2);
        //x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", RabbitMQConstant.DEAD_LETTER_EXCHANGE);
        //x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", RabbitMQConstant.DEAD_LETTER_ROUTING_KEY);
        return QueueBuilder.durable(RabbitMQConstant.ORDER_DELAY_EXPIRE_QUEUE_NAME).withArguments(args).build();
    }

    // 死信队列
    @Bean("deadLetterQueue")
    public Queue deadLetterQueue() {
        return new Queue(RabbitMQConstant.DEAD_LETTER_QUEUE_NAME);
    }

    // 普通订单Exchange和订单延迟队列绑定关系
    @Bean
    public Binding commonOrderExchangeBindingOrderDelayQueue(@Qualifier("orderDelayExpireQueue") Queue queue,
                                                             @Qualifier("commonOrderExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(RabbitMQConstant.ORDER_DELAY_EXPIRE_ROUTING_KEY).noargs();
    }

    // 死信Exchange和死信队列的绑定关系
    @Bean
    public Binding deadLetterExchangeBindingDeadLetterQueue(@Qualifier("deadLetterQueue") Queue queue,
                                                            @Qualifier("deadLetterExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(RabbitMQConstant.DEAD_LETTER_ROUTING_KEY).noargs();
    }
}

